package com.taplinker.client.im.util;

import java.io.FileOutputStream;
import java.io.InputStream;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public class TemplateUtil {
	private static final String FILE_NAME = "template_version";
	private static final String TMP_NAME = "tmp_name";
	private static final String VER_LOCAL = "local_version";
	private static final String VER_LATEST = "latest_version";
	
	private static void save(Context context, String name, String ver){
    	Editor editor = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE).edit();
    	editor.putString(name, ver);
    	editor.commit();
    	editor.clear();
    }
	
	private static String get(Context context, String name, String defVer) {
		SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
		return sp.getString(name, defVer);
	}
	
	public static void updateLocalVer(Context context, String ver){
		save(context, VER_LOCAL, ver);
	}
	
	public static void updateLatestVer(Context context, String ver){
		save(context, VER_LATEST, ver);
	}
	
	public static String getLocalVer(Context context, String defVer){
		return get(context, VER_LOCAL, defVer);
	}
	
	public static String getLatestVer(Context context, String defVer){
		return get(context, VER_LATEST, getLocalVer(context, defVer));
	}
	
	public static void saveTemplate(Context context, byte[] data) throws Exception {
		String tmpName = "tempate_" + getLatestVer(context, "v0.1") + ".tmp";
		save(context, TMP_NAME, tmpName);
		FileOutputStream fos = context.openFileOutput(tmpName, Context.MODE_PRIVATE);
		fos.write(data);
		fos.close();
    }
	
    public static InputStream getTemplate(Context context) throws Exception{
    	String tmpName = get(context, TMP_NAME, "tempate_v0.1.tmp");
    	return context.openFileInput(tmpName);
    }
}
